package com.changgou.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/****
 * 网关全局过滤器，用来判断是否携带JWT令牌
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    //用户请求参数|头文件|Cookie中令牌参数名字
    private static final String AUTHORIZATION_TOKEN = "Authorization";
    //用户登录页面
    private static final String LOGIN_URL = "http://192.168.38.68:9001/oauth/login";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //传入的请求的请求头中是否有令牌
        boolean hasToken = false;

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取url
        String path = request.getURI().getPath();
        if (path.startsWith("/api/user/login") || path.startsWith("/api/user/add") || URLFilter.noAuthorize(path)) {
            //不需要登录就能访问的页面，直接放行
            return chain.filter(exchange);
        }

        //其他请求进行拦截，获取令牌数据
        //从请求参数中获取令牌
        String token = request.getQueryParams().getFirst(AUTHORIZATION_TOKEN);

        if (StringUtils.isEmpty(token)) {
            //请求参数中没有则从请求头中获取
            token = request.getHeaders().getFirst(AUTHORIZATION_TOKEN);
            if (!StringUtils.isEmpty(token)) {
                hasToken = true;
            }
        }

        if (StringUtils.isEmpty(token)) {
            //请求头中也没有则从cookie中获取
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZATION_TOKEN);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }

        if (StringUtils.isEmpty(token)) {
            //如果令牌还没获得，则直接拦截跳转登录界面，在登录页面后面加上跳转过去的网址
            return needAuthorization(LOGIN_URL + "?FROM=" + request.getURI(), exchange);
            //设置错误状态码
            //response.setStatusCode(HttpStatus.METHOD_NOT_ALLOWED);
            //return response.setComplete();
        }

        //有令牌数据则进行解码，如果解码失败则抛出异常
        try {
            //JwtUtil.parseJWT(token);
            //将令牌添加到头文件发送给微服务
            if (!hasToken) {
                //请求头中没有令牌才需要进行添加
                request.mutate().header(AUTHORIZATION_TOKEN, "Bearer " + token);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //设置状态码，权限错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //解码成功则放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> needAuthorization(String url, ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", url);
        return response.setComplete();
    }
}
